package com.jsrana.idea.plugin.ideaweather;

import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerAdapter;
import com.intellij.openapi.wm.WindowManager;
import com.jsrana.idea.plugin.ideaweather.widget.WeatherStatusBarWidget;
import com.jsrana.idea.plugin.ideaweather.worker.WeatherWorker;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

/**
 * Created by Jitendra Rana on 7/14/14.
 */
public class IdeaWeatherPlugin
        implements ApplicationComponent {
    WeatherStatusBarWidget weatherStatusBarWidget;
    public static Map<String, String> weather = new HashMap<String, String>();
    public static List<Map<String, String>> forecast = new ArrayList<Map<String, String>>();
    public static boolean weatherWidgetMouseOverFlag = false;
    public static final String PROPERTY_WOEID = "QUICKWEATHER_WOEID";
    public static final String PROPERTY_LOCATION = "QUICKWEATHER_LOCATION";
    public static final String PROPERTY_UNIT = "QUICKWEATHER_UNIT";

    public static final String DEFAULT_WOEID = "2502265";
    public static final String DEFAULT_LOCATION = "Sunnyvale, CA, United States";
    public static final String DEFAULT_UNIT = "F";

    public IdeaWeatherPlugin() {
    }

    public void initComponent() {
        ProjectManager.getInstance().addProjectManagerListener( new ProjectManagerAdapter() {
            @Override
            public void projectOpened( Project project ) {
                super.projectOpened( project );
                weatherStatusBarWidget = new WeatherStatusBarWidget();
                WindowManager.getInstance().getStatusBar( project ).addWidget( weatherStatusBarWidget );
                new java.util.Timer().schedule( new WeatherTask(), 100, 2 * 60 * 60 * 1000 );
            }

            @Override
            public void projectClosing( Project project ) {
                super.projectClosing( project );
                WindowManager.getInstance().getStatusBar( project ).removeWidget( weatherStatusBarWidget.ID() );
            }
        } );
    }

    public void disposeComponent() {
        // TODO: insert component disposal logic here
    }

    @NotNull
    public String getComponentName() {
        return "IdeaWeatherPlugin";
    }

    class WeatherTask
            extends TimerTask {
        @Override public void run() {
            new WeatherWorker().execute();
        }
    }
}
